package com.lyf.shop.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.lyf.shop.entity.Car;
import com.lyf.shop.service.CarService;
import com.lyf.shop.vo.CartItemVo;
import com.lyf.shop.vo.CartVo;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * (Car)表控制层
 *
 * @author makejava
 * @since 2021-12-03 14:45:41
 */
@Controller
@RequestMapping("car")
public class CarController {
    /**
     * 服务对象
     */
    @Resource
    private CarService carService;

    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @GetMapping("selectOne")
    public Car selectOne(Integer id) {
        return this.carService.queryById(id);
    }

    /**
     * 去往购物车页面，获取购物车对象
     * @param num
     * @param pid
     * @param model
     * @return
     * @throws JsonProcessingException
     */
    @RequestMapping("toCart")
    public String toCart(@RequestParam(value = "num",required = false,defaultValue = "0")int num, @RequestParam(value = "pid",required = false,defaultValue = "-1")int pid, Model model) throws JsonProcessingException {
        // 初始化数据
        CartVo cartVo = carService.getCart();
        //新增数据到购物车
        if (num!=0&&pid!=-1) {
            carService.addCartItem(cartVo, pid, num);
        }
        model.addAttribute("cart",cartVo);
        System.out.println(cartVo);
        System.out.println("打印cartvo"+cartVo.getTotalPrice());
        return "jsp/car";
    }

    /**
     * 删除对应的购物车项
     * @param pid
     * @param model
     * @return
     * @throws JsonProcessingException
     */
    @RequestMapping("deleteCartItem")
    public String deleteCartItem(@RequestParam("pid")int pid,Model model) throws JsonProcessingException {
        CartVo cart = carService.getCart();
        carService.deleteCartItem(cart,pid);
        model.addAttribute("cart",cart);
        return "jsp/car";
    }

    /**
     * 改变某个购物车项勾选状态
     * @param pid
     * @param model
     * @return
     * @throws JsonProcessingException
     */
    @RequestMapping("changeChecked")
    public String changeChecked(@RequestParam("pid")int pid,Model model) throws JsonProcessingException {
        CartVo cart = carService.getCart();
        carService.changeChecked(cart,pid);
        model.addAttribute("cart",cart);
        return "jsp/car";
    }

    /**
     * 改变某个购物车项的数量
     * @param pid
     * @param num
     * @param model
     * @return
     * @throws JsonProcessingException
     */
    @RequestMapping("changeCartItemNum")
    public String changeCartItemNum(@RequestParam("pid")int pid,@RequestParam("num")int num,Model model) throws JsonProcessingException {
        CartVo cart = carService.getCart();
        carService.changeCartItemNum(cart,pid,num);
        model.addAttribute("cart",cart);
        return "jsp/car";
    }

}